<template>
  <view class="button-group" style="height:100%">
    <view class="button-group ">
      <button v-if="!isAllTk&&buttonText == '全部退款'" class="cu-btn g-button margin-tb-sm lg"
        @click="onRefund">{{buttonText}}</button>
      <button v-else-if="buttonText == '部分退款'" class="cu-btn g-button margin-tb-sm lg"
        @click="onRefund">{{buttonText}}</button>
    </view>

    <uni-popup ref="popupUpdate" type="center" :mask-click="false" v-if="orderNo" :key="orderNo">
      <uni-card class="show-y-scroll-bar" style="overflow: inherit;max-height: 80vh;overflow-y: scroll;">
        <template v-slot:title>
          <view class="flex solid-bottom padding justify-between text-lg">
            <view class="text-lg">{{buttonText}} 订单:{{orderNo}}</view>
            <text class="cuIcon-close" @click="close"></text>
          </view>
        </template>
        <view class="uni-body uni-mt-5">
          <uni-forms :modelValue="formModelData" :label-width="'15rem'">
            <bUpdate ref="bUpdate" :custGridHeader="config.listHeaders" heightTop="20rem" :page="config.page"
              :editorType="type" :config="config" @on-list-item-checked="onItemChecked" :condition="config.condition"
              @change="onListChange">
            </bUpdate>
            <uni-forms-item class="flex align-center" :label="'退款原因'" :required="true" :name="'refund_reason'">
              <!-- <view class="flex align-center"> -->
              <uni-data-checkbox selectedColor="#38c09e" mode="tag" v-model="formModelData['refund_reason']"
                :localdata="refundReason">
              </uni-data-checkbox>
              <uni-easyinput v-if="formModelData['refund_reason']==='自定义'" v-model="formModelData['custom_reason']"
                placeholder="" type="text" primaryColor="#38c09e" />
              <!-- </view> -->
              <!-- <uni-data-select 
									type="line"
										      v-model="formModelData['refund_reason']"
										      :localdata="refundReason"
									></uni-data-select> -->
            </uni-forms-item>
            <!-- 								<uni-forms-item :label="'退款方式'"
									:name="'refund_reason'">
									<uni-data-checkbox mode="button" v-model="formModelData['refund_method']" :localdata="refundMethod"></uni-data-checkbox>
								</uni-forms-item> -->
            <view class="form-item">
              <text class="text-bold form-item-label">退款金额:</text>
              <text class="form-item-coutent text-red" v-if="type==='part'">{{refundAmount||0}}</text>
              <text class="form-item-coutent text-red" v-else>
                {{setColumnText(formModelData.order_amount||formModelData.pay_amount)}}
                <!-- {{formModelData.order_amount||formModelData.pay_amount}} -->
              </text>
            </view>
            <view class="form-item">
              <text class="text-bold form-item-label">退款方式:</text><text
                class="form-item-coutent">{{ formModelData.refund_method || '原路退回' }}
              </text>
            </view>
            </uni-section>
          </uni-forms>
        </view>
        <view slot="actions" class="card-actions button-group padding-lg border-top margin-bottom"
          style="justify-content: center;">
          <button class="card-actions-item cu-btn button lg margin-right-lg" @click="close" type="info">
            <text class="card-actions-item-text">取消</text>
          </button>
          <button class="card-actions-item cu-btn button lg" type="primary" @click="actionsClick('submit')">
            <text class="card-actions-item-text">确认</text>
          </button>
        </view>
      </uni-card>
    </uni-popup>
  </view>
</template>

<script>
  import bUpdate from '@/components/g-batch-update/g-batch-update-child.vue'
  export default {
    components: {
      bUpdate
    },
    data() {
      return {
        isAllTk: false,
        config: {
          serviceName: "srvretail_order_select",
          listLayout: "batchList", // listAndDetail listAndFilter  list  batchList
          defaultData: "batch-select ", // batch-select   service-loading
          detailPath: "simple", //  simple  基础的； 或者配置页面路由 路由格式待定
          page: {
            pageNo: 1,
            rownumber: 20
          },
          // listHeaders: ['goods_name', 'goods_price', 'goods_num', 'subtotal_amount', 'refund_num',
          //   'refund_subtotal'
          // ],
          listHeaders: ['goods_name', 'sale_price', 'goods_num', 'subtotal_amount', 'goods_num',
            'ctual_amount'
          ],
          childService: "srvretail_order_detail_select",
          childKeyCol: "order_no", // 子表数据的主键
          childKeyVal: null, // 子表外键val
          tabsType: "custom", //
          titleText: "返回",
          title: "",
          popupColumns: ["refund_num", "goods_price", "refund_subtotal"],
          custTabs: [{
            "colName": "goods_barcode",
            "type": "input",
            "inputType": "String",
            "parent": "",
            "is_count": false,
            "show_expr": {},
            "label": "商品条码",
            "showLabel": true,
            "default": "",
            "colspan": 24,
            "showAllTag": false,
            "tags": [],
            "appendSearchButton": true
          }],
          tabs: {
            layout: 'inline', // 'inline'   block
          },
          condition: [],
        },
        refundReason: [],
        mainV2Loaded: false,
        mainV2: null,

        formModelData: {
          order_no: "",
          refund_method: "原路退回",
          refund_reason: "",
          refund_amount: "",
          custom_reason: ""
        },
        mainData: null,
        refundMethod: null,
        // reu
        listData: [],
        refundAmount: 0,
        onHandler: false
      };
    },
    props: {
      type: {
        type: String, //  part   all
        default: "all"
      },
      orderNo: {
        type: String,
        default: ""
      },
      serviceName: {
        type: String,
        default: "srvretail_refund_order_add"
      }
    },
    computed: {
      buttonText: function() {
        switch (this.type) {
          case 'part':
            return '部分退款'
          case 'all':
            return '全部退款'
            break;
          default:
            break;
        }
      },
      formModelFields: function() {
        let fields = this.mainV2._fieldInfo || []
        return fields
      }

    },
    created() {

    },
    methods: {
      onListChange(e) {
        if (this.type === 'part') {
          this.$nextTick(() => {
            let data = this.childGoodsInfo()
            if (Array.isArray(data) && data.length > 0) {
              this.refundAmount = data.reduce((res, cur) => {
                if (cur.refund_subtotal) {
                  res += cur.refund_subtotal
                }
                return Number(Number(res).toFixed(2))
              }, 0)
            }
          })
        }
      },
      getMainData(pageNo, type) {
        let self = this
        let req = {
          "serviceName": "srvretail_store_order_select",
          "colNames": [
            "*"
          ],
          "condition": [{
            "colName": "order_no",
            "ruleType": "eq",
            "value": this.orderNo
          }],
          "page": {
            "pageNo": 1,
            "rownumber": 1
          }
        }
        this.$fetch('select', 'srvretail_store_order_select', req).then((res) => {
          if (res.success) {
            this.mainData = res.data[0]
            this.$set(this.formModelData, 'order_no', this.mainData.order_no)
            this.$set(this.formModelData, 'refund_method', this.mainData.refund_method || this.mainData
              .payment_method)
            this.$set(this.formModelData, 'pay_amount', this.mainData.pay_amount)
            this.$set(this.formModelData, 'refund_amount', this.mainData.refund_amount)
            this.$set(this.formModelData, 'order_amount', this.mainData.order_amount)
            this.$set(this.formModelData, 'store_no', this.mainData.store_no)
            this.$set(this.formModelData, 'member_no', this.mainData.member_no)
            this.$set(this.formModelData, 'member_name', this.mainData.member_name)
          }
        })

      },
      onRefund() {
        this.geiMainV2()
        this.config.condition.push({
          colName: "order_no",
          ruleType: 'eq',
          value: this.orderNo
        })
        this.config.childKeyVal = this.orderNo
        this.$refs.popupUpdate.open()
        this.$refs.bUpdate?.getPageConfig()
      },
      close() {
        this.$refs.popupUpdate.close()
      },
      onItemChecked(e) {
        console.log(e)
      },
      geiMainV2() {
        // srvretail_refund_order_add
        let self = this
        if (!this.mainV2Loaded) {
          this.getServiceV2(this.serviceName, 'add', 'add').then((res) => {
            this.mainV2 = res
            this.mainV2Loaded = true
            console.log('getServiceV2 mainV2', res._fieldInfo)
            for (let field of res._fieldInfo) {
              if (field.columns == 'refund_reason') {
                this.refundReason = field.options.map((item) => {
                  let col = {
                    text: item.label,
                    value: item.value
                  }
                  return col
                })

              }
              // if( field.columns == 'refund_method'){
              // 	this.refundMethod = field.options.map((item) =>{
              // 		let col = {
              // 			text:item.label,
              // 			value:item.value
              // 		}
              // 		return col
              // 	})
              // }
            }
            this.getMainData()
          })
        } else {
          this.getMainData()
        }

      },
      actionsClick(type) {
       
        let btnType = type || ''
        let self = this
        let itemBarcode = self.checkedItem ? self.checkedItem['goods_barcode'] : ""
        let formModel = self.formData
        this.submitRequest()
      },
      childGoodsInfo() {
        let self = this
        let datas = []
        let data = {}
        let listData = self.$refs.bUpdate.getTableData()
        for (let item of listData) {
          data = {
            goods_no: null,
            goods_barcode: null,
            goods_name: null,
            refund_num: null,
            refund_price: null,
            refund_subtotal: null,
            sale_subtotal: null
          }
          data.goods_no = item.goods_no
          data.goods_barcode = item.goods_barcode
          data.goods_name = item.goods_name
          data.refund_num = this.type === 'all' ? item.goods_num : item.refund_num
          data.refund_price = item.ctual_amount / item.goods_num
          data.refund_subtotal = item.ctual_amount 
          data.sale_subtotal = item.subtotal_amount
          data.order_detail_no = item.order_detail_no
          if (this.type === 'all') {
            datas.push(data)
          } else if (this.type === 'part') {
            if (data.refund_num) {
              data.refund_subtotal = Number(Number(data.refund_num * data.refund_price).toFixed(2))
              datas.push(data)
            }
          }

        }
        return datas
      },
      submitRequest(type) {
        if (this.onHandler === true) {
          return
        }
        this.onHandler = true
        setTimeout(() => {
          this.onHandler = false
        }, 3000)
        let self = this
        let srv = 'srvretail_refund_order_add'
        let datas = self.childGoodsInfo();
        if (!this.formModelData.refund_reason) {
          uni.showToast({
            title: '请选择退款原因',
            icon: 'none'
          })
          return
        }
        if (this.formModelData.refund_reason === '自定义' && !this.formModelData.custom_reason) {
          uni.showToast({
            title: '请填写自定义退款原因',
            icon: 'none'
          })
          return
        }
        if (this.type === 'part') {
          if (!datas.find(item => item.refund_num && !isNaN(item.refund_num).refund_num > 0)) {
            uni.showToast({
              title: '部分退款至少需要有一个商品退货数量大于0',
              icon: 'none'
            })
            return
          }
        }
        let req = [{
          "serviceName": 'srvretail_refund_order_add',
          "condition": [],
          "data": [{
            "child_data_list": [{
              "serviceName": 'srvretail_refund_detail_add',
              "condition": [],
              "depend_keys": [{
                "type": "column",
                "add_col": 'refund_no',
                "depend_key": 'refund_no'
              }],
              "data": self.childGoodsInfo()
            }]
          }]
        }]
        // formModelData:{
        // 	order_no:"",
        // 	refund_method:"",
        // 	refund_reason:"",
        // 	refund_amount:""
        // }
        req[0].data[0]['order_no'] = this.formModelData.order_no
        req[0].data[0]['refund_method'] = this.formModelData.refund_method || '原路退回'
        req[0].data[0]['refund_reason'] = this.formModelData.refund_reason
        req[0].data[0]['custom_reason'] = this.formModelData.custom_reason
        req[0].data[0]['refund_amount'] = this.formModelData.pay_amount || this.formModelData.refund_amount || this
          .formModelData.order_amount
        if (this.type === 'part') {
          req[0].data[0]['refund_amount'] = self.childGoodsInfo().reduce((res, cur) => {
            if (cur.refund_subtotal) {
              res += cur.refund_subtotal
            }
            return res
          }, 0)
        }
        req[0].data[0]['store_no'] = this.formModelData.store_no
        req[0].data[0]['member_no'] = this.formModelData.member_no
        req[0].data[0]['member_name'] = this.formModelData.member_name
        req[0].data[0]['channel_source'] = '台式消费机'
        req[0].data[0]['child_data_list'][0].data = self.childGoodsInfo()
        uni.showLoading({
          title:'请稍等'
        })
        self.$fetch('operate', srv, req).then((res) => {
          uni.hideLoading()
          if (res.success) {
            uni.showToast({
              icon: "none",
              title: '提交退款申请成功'
            })
            self.close();
            self.isAllTk = true;
            self.$emit('submit-refund-order', true)

          } else {
            uni.showToast({
              icon: "none",
              title: res.resultMessage
            })
          }
        })

      }

    }
  }
</script>

<style lang="scss">
  .cu-btn:not([class*="bg-"]) {
    background-color: auto;
  }

  ::v-deep .checklist-box.uni-label-pointer.is--tag {
    line-height: 6.8rem;
    height: 6.8rem;
    font-size: 2.4rem;
    min-width: 17rem;

    .checklist-content {
      text-align: center;
      justify-content: center;
    }

    .checklist-text {
      font-size: 2.4rem !important;
    }
  }

  .uni-forms-item {
    align-items: flex-start;
  }

  .form-item {
    font-size: 2.4rem;

    &-label {
      display: inline-block;
    }
  }
</style>
